package cn.terrence.myrpc.common.registercenter.zookeeper;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkInterruptedException;



/**
 * @author zhangshuquan
 * @date 2017年12月29日 14时54分42秒
 * @description zkClient工具类
 */
public class ZkClientProxy {
	
	private static ZkClientContext context;
	
    private ZkClientProxy(){
    	
    }
    
    static{
    	context = new ZkClientContext();
    	context.setIpWithPorts("127.0.0.1:2181");
    	context.setSessionTimeout(1000*60);
    	context.setConnectionTimeout(1000*60);
    }
    
    /**
     * 获取ZkClient连接对象
     * @return
     */
    public ZkClient getInstance() {
    	return new ZkClient(context.getIpWithPorts(),context.getSessionTimeout(),context.getConnectionTimeout());
    }
    
    
    public void save(String node) throws Exception {
    	ZkClient zkClient = null;
        try {
            zkClient = getInstance();
            if (zkClient.exists(node)){
                throw new Exception("配置项已存在!");
            }
            zkClient.createPersistent(node, true);
            zkClient.writeData(node,node);
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            try {
                zkClient.close();
            } catch (ZkInterruptedException e) {
                throw new Exception(e);
            }
        }
    }
}
